package com.cy.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class ServiceBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        httpServletResponse.setCharacterEncoding("utf-8");
        //httpServletResponse.setContentType("text/html;charset=utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        Map<String, Object> map = new HashMap<>();
        map.put("status",429);
        if (e instanceof DegradeException){//降级异常
                //out.println("服务暂时不可用");
            map.put("message","服务暂时不可用");
        }else {
                //out.println("访问太频繁，稍等片刻再访问");
            map.put("message","访问太频繁，稍等片刻再访问");
        }
        String jsonStr = new ObjectMapper().writeValueAsString(map);
        out.println(jsonStr);
        out.flush();
    }
}
